package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.TOrders;
import com.ruoyi.system.domain.TTakeoutLog;
import com.ruoyi.system.domain.vo.ProductReviewVO;
import com.ruoyi.system.service.ITOrdersService;
import com.ruoyi.system.service.ITTakeoutLogService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TProductReviews;
import com.ruoyi.system.service.ITProductReviewsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品评价Controller
 *
 * @author ruoyi
 * @date 2025-07-08
 */
@RestController
@RequestMapping("/system/reviews")
public class TProductReviewsController extends BaseController {
    @Autowired
    private ITProductReviewsService tProductReviewsService;
    @Autowired
    private ITOrdersService tOrdersService;
    @Autowired
    private ITTakeoutLogService takeoutLogService;

    /**
     * 查询商品评价列表
     */
    @PreAuthorize("@ss.hasPermi('system:reviews:list')")
    @GetMapping("/list")
    public TableDataInfo list(TProductReviews tProductReviews) {
        startPage();
        List<TProductReviews> list = tProductReviewsService.selectTProductReviewsList(tProductReviews);
        return getDataTable(list);
    }

    /**
     * 导出商品评价列表
     */
    @PreAuthorize("@ss.hasPermi('system:reviews:export')")
    @Log(title = "商品评价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TProductReviews tProductReviews) {
        List<TProductReviews> list = tProductReviewsService.selectTProductReviewsList(tProductReviews);
        ExcelUtil<TProductReviews> util = new ExcelUtil<TProductReviews>(TProductReviews.class);
        util.exportExcel(response, list, "商品评价数据");
    }

    /**
     * 获取商品评价详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:reviews:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tProductReviewsService.selectTProductReviewsById(id));
    }

    /**
     * 新增商品评价
     */
    @PreAuthorize("@ss.hasPermi('system:reviews:add')")
    @Log(title = "商品评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TProductReviews tProductReviews) {
        return toAjax(tProductReviewsService.insertTProductReviews(tProductReviews));
    }

    /**
     * 修改商品评价
     */
    @PreAuthorize("@ss.hasPermi('system:reviews:edit')")
    @Log(title = "商品评价", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TProductReviews tProductReviews) {
        return toAjax(tProductReviewsService.updateTProductReviews(tProductReviews));
    }

    /**
     * 删除商品评价
     */
    @PreAuthorize("@ss.hasPermi('system:reviews:remove')")
    @Log(title = "商品评价", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tProductReviewsService.deleteTProductReviewsByIds(ids));
    }

    /**
     * wx用户查询商品评价列表
     */
    @PostMapping("/getReviewsList")
    public AjaxResult getReviewsList(@RequestBody TProductReviews tProductReviews) {
        // 处理 rating 参数
        if (tProductReviews.getRating() != null) {
            switch (tProductReviews.getRating()) {
                case 5: // 好评（4+5）
                    tProductReviews.setRatings(Arrays.asList(4, 5));
                    break;
                case 3: // 中评（2+3）
                    tProductReviews.setRatings(Arrays.asList(2, 3));
                    break;
                case 1: // 差评（1）
                    tProductReviews.setRatings(Arrays.asList(1));
                    break;
                case 0: // 全部（1+2+3+4+5）
                    tProductReviews.setRatings(Arrays.asList(1, 2, 3, 4, 5));
                    break;
                default: // 其他情况（如单独查询 2 星）
                    tProductReviews.setRatings(Arrays.asList(tProductReviews.getRating()));
            }
            tProductReviews.setRating(null); // 避免干扰
        }

        // 调用 Service 层
        List<ProductReviewVO> list = tProductReviewsService.getReviewsList(tProductReviews);
        return AjaxResult.success(list);
    }

    /**
     * wx用户新增商品评价
     */
    @Log(title = "商品评价", businessType = BusinessType.INSERT)
    @PostMapping("{addByUser}")
    public AjaxResult addByUser(@RequestBody TProductReviews tProductReviews) {   // 插一条订单
        TOrders orders = new TOrders();
        orders.setId(tProductReviews.getOrderId());
        orders.setOrderStatus(5L); // 订单状态（5表示"已完成"）
        orders.setCancelTime(new Date()); // 取消时间
        orders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(orders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("已完成");
        tTakeoutLog.setOrderId(tProductReviews.getOrderId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        tProductReviews.setUserId(SecurityUtils.getUserId());
        tProductReviews.setStatus(1);
        return toAjax(tProductReviewsService.insertTProductReviews(tProductReviews));
    }


    /**
     * wx用户修改商品评价(增加点赞数)
     */
//    @Log(title = "商品评价", businessType = BusinessType.UPDATE)
    @PutMapping("/editReviews")
    public AjaxResult editReviews(@RequestBody TProductReviews tProductReviews) {
        //方法1
//         update productReviews set LikeCoun = LikeCoun + 1 where id = #{id}
        tProductReviewsService.updateLikeCount(tProductReviews.getId());

//    //方法2(缺陷：几个用户同时点赞时， LikeCount 计算错误)
//        //查评论id
//        TProductReviews productReviews = tProductReviewsService.selectTProductReviewsById(tProductReviews.getId());
//        // 点赞数 +1
//        productReviews.setLikeCount(productReviews.getLikeCount() + 1);
//        //更新总数
//        tProductReviewsService.updateTProductReviews(productReviews);

        return AjaxResult.success("点赞成功");
    }

    /**
     * 获取商品评价平均值
     */
    @GetMapping(value = "/getAverageRating")
    public AjaxResult getAverageRating() {
        Double  averageRating = tProductReviewsService.selectAverageRating();
        return AjaxResult.success(averageRating);
    }

}
